﻿using FFmpeg.AutoGen;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FFmpegLib
{
    public sealed unsafe class PcmFrame : IDisposable
    {
        public static readonly AVRational TimeBaseQ = new AVRational { num = 1, den = ffmpeg.AV_TIME_BASE };

        private void* pcm;
        public void* Pcm { get => pcm; }
        public int Size { get; set; }
        public int NbSamples { get; set; }
        public int Channels { get; set; }
        public int SampleRate { get; set; }
        public long Pts { get; set; }
        /// <summary>
        /// 单位ms
        /// </summary>
        public long NewPts { get; private set; }

        private AVRational TimeBase;

        public PcmFrame(int channels, int nbSamples, AVSampleFormat fmt)
        {
            int size = FFmpegUtils.GetBufferSize(channels, nbSamples, fmt);
            IntPtr data = System.Runtime.InteropServices.Marshal.AllocHGlobal(size);
            pcm = data.ToPointer();
            Size = size;
            Channels = channels;
            NbSamples = nbSamples;
        }

        public void InitPts(long pts, AVRational timeBase)
        {
            Pts = pts;
            NewPts = ffmpeg.av_rescale_q(Pts, timeBase, TimeBaseQ) / 1000;
        }

        #region
        private bool disposedValue;
        protected void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    // TODO: 释放托管状态(托管对象)
                    if (pcm != null)
                        System.Runtime.InteropServices.Marshal.FreeHGlobal((IntPtr)pcm);
                }
                disposedValue = true;
            }
        }

        public void Dispose()
        {
            // 不要更改此代码。请将清理代码放入“Dispose(bool disposing)”方法中
            Dispose(disposing: true);
            GC.SuppressFinalize(this);
        }
        #endregion

    }
}